class NavMenuManager {
  constructor() {
    this.menuSelector = '#newNavMenu';
    this.menuItemSelector = 'span.ygSKg';
    this.submenuSelector = '.byted-menu';
    this.submenuItemSelector = '.byted-submenu';
    this.currentMenuItem = null;
  }

  /**
   * 提取导航菜单项
   * @param {string} menuSelector - 菜单选择器
   * @returns {Array} 菜单项数组
   */
  extractMenuItems(menuSelector = this.menuSelector) {
    const navMenu = document.querySelector(menuSelector);
    if (!navMenu) return [];

    const items = navMenu.querySelectorAll(this.menuItemSelector);
    return Array.from(items).map(item => ({
      id: item.id,
      text: item.textContent.trim(),
      element: item
    }));
  }

  /**
   * 提取二级菜单项
   * @returns {Array} 二级菜单项数组
   */
  extractSubmenuItems() {
    const menuRoot = document.querySelector(this.submenuSelector);
    if (!menuRoot) return [];

    const submenuList = menuRoot.querySelectorAll(this.submenuItemSelector);
    const result = [];

    submenuList.forEach(submenu => {
      const groupTitleEl = submenu.querySelector('.byted-submenu-header .byted-menu-line-title');
      const groupTitle = groupTitleEl ? groupTitleEl.textContent.trim() : '';

      const itemEls = submenu.querySelectorAll('.byted-submenu-content .byted-menu-item');
      const items = Array.from(itemEls).map(item => {
        const itemSpan = item.querySelector('.gXNZm');
        return {
          id: itemSpan?.id || '',
          text: itemSpan?.textContent.trim() || '',
          element: item
        };
      });

      result.push({ 
        groupTitle, 
        items,
        element: submenu
      });
    });

    return result;
  }

  /**
   * 切换到指定的菜单项
   * @param {string} menuText - 菜单项文本
   * @returns {boolean} 是否切换成功
   */
  async switchToMenuItem(menuText) {
    const menuItems = this.extractMenuItems();
    const targetItem = menuItems.find(item => item.text === menuText);
    
    if (!targetItem) {
      console.warn(`未找到菜单项: ${menuText}`);
      return false;
    }

    try {
      targetItem.element.click();
      this.currentMenuItem = targetItem;
      return true;
    } catch (error) {
      console.error('切换菜单项失败:', error);
      return false;
    }
  }

  /**
   * 切换到指定的二级菜单项
   * @param {string} groupTitle - 分组标题
   * @param {string} itemText - 菜单项文本
   * @returns {boolean} 是否切换成功
   */
  async switchToSubmenuItem(groupTitle, itemText) {
    const submenuItems = this.extractSubmenuItems();
    const targetGroup = submenuItems.find(group => group.groupTitle === groupTitle);
    
    if (!targetGroup) {
      console.warn(`未找到菜单分组: ${groupTitle}`);
      return false;
    }

    const targetItem = targetGroup.items.find(item => item.text === itemText);
    if (!targetItem) {
      console.warn(`未找到菜单项: ${itemText}`);
      return false;
    }

    try {
      // 如果分组是折叠的，先展开
      if (targetGroup.element.classList.contains('byted-submenu-collapsed')) {
        const header = targetGroup.element.querySelector('.byted-submenu-header');
        if (header) header.click();
        // 等待展开动画完成
        await new Promise(resolve => setTimeout(resolve, 300));
      }

      targetItem.element.click();
      return true;
    } catch (error) {
      console.error('切换二级菜单项失败:', error);
      return false;
    }
  }

  /**
   * 获取当前激活的菜单项
   * @returns {Object|null} 当前激活的菜单项
   */
  getCurrentMenuItem() {
    const menuItems = this.extractMenuItems();
    const activeItem = menuItems.find(item => 
      item.element.classList.contains('active') || 
      item.element.getAttribute('aria-selected') === 'true'
    );
    return activeItem || null;
  }

  /**
   * 获取当前激活的二级菜单项
   * @returns {Object|null} 当前激活的菜单项
   */
  getCurrentSubmenuItem() {
    const submenuItems = this.extractSubmenuItems();
    for (const group of submenuItems) {
      const activeItem = group.items.find(item => 
        item.element.classList.contains('byted-menu-item-selected') ||
        item.element.getAttribute('aria-selected') === 'true'
      );
      if (activeItem) {
        return {
          groupTitle: group.groupTitle,
          ...activeItem
        };
      }
    }
    return null;
  }

  /**
   * 监听菜单变化
   * @param {Function} callback - 变化回调函数
   */
  observeMenuChanges(callback) {
    const observer = new MutationObserver((mutations) => {
      const currentItem = this.getCurrentMenuItem();
      const currentSubmenuItem = this.getCurrentSubmenuItem();
      
      if (currentItem && currentItem !== this.currentMenuItem) {
        this.currentMenuItem = currentItem;
        callback({
          type: 'main',
          item: currentItem
        });
      }

      if (currentSubmenuItem) {
        callback({
          type: 'submenu',
          item: currentSubmenuItem
        });
      }
    });

    const navMenu = document.querySelector(this.menuSelector);
    const submenuRoot = document.querySelector(this.submenuSelector);
    
    if (navMenu) {
      observer.observe(navMenu, {
        childList: true,
        subtree: true,
        attributes: true,
        attributeFilter: ['class', 'aria-selected']
      });
    }

    if (submenuRoot) {
      observer.observe(submenuRoot, {
        childList: true,
        subtree: true,
        attributes: true,
        attributeFilter: ['class', 'aria-selected']
      });
    }
  }
}

// 创建并导出实例
const navMenuManager = new NavMenuManager();
export { navMenuManager }; 